<?php

namespace app\api\controller;

use think\Db;
use app\common\validate\AddressValidate;

class Address extends ApiBase
{
	
	protected $datas;

	/**
	 * 添加收货地址
	 * @Author   Yichen
	 * @DateTime 2020-05-05T17:16:06+0800
	 */
	public function addAddress()
	{
		$this->datas = $this->params;
		$validate = new AddressValidate();
		if (!$validate->scene('add')->check($this->datas)) {
			return json(['code' => 0, 'msg' => $validate->getError(), 'data' => '']);
		}
		$userId = session('userinfo.uid');
		$addressInfo = $this->datas['addressInfo'];
		$detailed = $this->datas['detailed'];
		$consignee = $this->datas['consignee'];
		$phone = $this->datas['phone'];
		$zipCode = !empty($this->datas['zipCode']) ? $this->datas['zipCode'] : '000000';
		$isDefault = isset($this->datas['isDefault']) ? $this->datas['isDefault'] : 0;
		$id = isset($this->datas['id']) ? $this->datas['id'] : '';
		$addressArr = explode('/', $addressInfo);
		$comName = str_replace('/', '', $addressInfo) . $detailed;
		$isExist = Db::name('t_address')
			->where([
				'user_id' => $userId,
				'com_name' => $comName,
				'consignee' => $consignee,
				'zip_code' => $zipCode,
				'phone' => $phone
			])->find();
		if (!empty($isExist)) {
			return json(['code' => 0, 'msg' => '该地址已存在', 'data' => '']);
		}	
		$data = [
			'user_id' => $userId,
			'province' => $addressArr[0],
			'city' => $addressArr[1],
			'region' => $addressArr[2],
			'street' => $addressArr[3],
			'detailed' => $detailed,
			'com_name' => $comName,
			'consignee' => $consignee,
			'phone' => $phone,
			'zip_code' => $zipCode
		];
		if (!empty($id)) {
			$data['update_time'] = time();
			$result = Db::name('t_address')->where('id', $id)->update($data);
			if ($isDefault == 1) {
				$this->_set($id, $userId);
			}
		} else {
			$data['create_time'] = time();
			$result = Db::name('t_address')->insertGetId($data);
			$this->_set($result, $userId);
		}
		if (!$result) {
			return json(['code' => 0, 'msg' => '添加失败', 'data' => '']);
		}
		return json(['code' => 1, 'msg' => '添加成功', 'data' => '']);
	}

	/**
	 * 获取地址列表
	 * @Author   Yichen
	 * @DateTime 2020-05-05T17:44:01+0800
	 * @param    [type]                   $userId [description]
	 * @return   [type]                           [description]
	 */
	public function addressList()
	{
		$userId = session('userinfo.uid');
		if (empty($userId)) {
			return json(['code' => 4, 'msg' => '请登录', 'data' => []]);
		}
		$data = Db::name('t_address')
			->where('user_id', $userId)
			->order('update_time', 'desc')
			->order('create_time', 'desc')
			->field('id,consignee,province,city,region,street,detailed,phone,zip_code zipCode, is_default isDefault')
			->select();
		return json(['code' => 1, 'msg' => '', 'data' => $data]);	
	}

	/**
	 * 删除地址
	 * @Author   Yichen
	 * @DateTime 2020-05-07T21:47:48+0800
	 * @return   [type]                   [description]
	 */
	public function delAddress()
	{
		$this->datas = $this->params;
		$validate = new AddressValidate();
		if (!$validate->scene('del')->check($this->datas)) {
			return json(['code' => 0, 'msg' => $validate->getError(), 'data' => '']);
		}
		$addressId = $this->datas['id'];
		$result = Db::name('t_address')->where('id', $addressId)->delete();
		if (!$result) {
			return json(['code' => 0, 'msg' =>'删除失败', 'data' => '']);
		}
		return json(['code' => 1, 'msg' =>'删除成功', 'data' => '']);
	}

	/**
	 * 设置为默认
	 * @Author   Yichen
	 * @DateTime 2020-05-07T22:22:24+0800
	 */
	public function setDefault()
	{
		$this->datas = $this->params;
		$validate = new AddressValidate();
		if (!$validate->scene('set')->check($this->datas)) {
			return json(['code' => 0, 'msg' => $validate->getError(), 'data' => '']);
		}
		$addressId = $this->datas['id'];
		$uid = session('userinfo.uid');
		$result = $this->_set($addressId, $uid);
		if (!$result) {
			return json(['code' => 0, 'msg' => '失败', 'data' => '']);
		}
		return json(['code' => 1, 'msg' => '成功', 'data' => '']);
	}

	/**
	 * 设置默认
	 * @Author   Yichen
	 * @DateTime 2020-05-07T22:38:40+0800
	 */
	protected function _set($addressId, $uid)
	{
		Db::startTrans();
		try {
			Db::name('t_address')->where('id', $addressId)->update(['is_default' => 1]);
			Db::name('t_address')
				->where('user_id', $uid)
				->where('id', '<>', $addressId)
				->update(['is_default' => 0]);
			Db::commit();
			$result = 1;
		} catch  (\Exception $e) {
			$result = 0;
			Db::rollback();
		}
		return $result;
	}
}